package top.zhangjianyong.tools.config.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.zhangjianyong.tools.utils.ApiResponse;
import top.zhangjianyong.tools.utils.ExceptionUtil;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ： zhangjianyong
 * @date ： 2022/10/14 2:09 PM
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResponse error(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String respMessage = allErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return ApiResponse.fail(respMessage);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResponse error(Exception e) {
        log.error(e.getMessage(), e);
        return ApiResponse.fail(e.getMessage(), ExceptionUtil.getExceptionToString(e));
    }
}
